<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .canvas {
            border: 1px solid red;
        }
        #offCanvas{
            border: 1px solid red;
            display: none;
        }
    </style>
</head>
<body>
<canvas class="canvas" width="600px" height="400px">
    您的浏览器不支持
</canvas>
<!--创建离屏canvas-->
<canvas id="offCanvas" width="600px" height="400px">
    您的浏览器不支持
</canvas>

<script>
  var canvas = document.getElementsByClassName('canvas')[0]
  var offCanvas = document.getElementById('offCanvas')
  var ctx = canvas.getContext('2d')
  var ctx2 = offCanvas.getContext('2d')

  var posx = 0, posy = 0, dir = 1,isMouseInRect = false;
  //把一些复杂的绘画操作，画在离屏Canvas上面
  var drawAlot = function(){
    for(var k=0;k<20;k++){
      for(var i=0;i<canvas.width;i+=10){
        for(var j=0;j<canvas.height;j+=10){
          ctx2.beginPath()
          ctx2.arc(i,j,5,0,Math.PI*2,true)
          ctx2.stroke()
        }
      }
    }
  }
   canvas.onmousemove = function(e){
    var mouseX = e.offsetX
    var mouseY = e.offsetY
     if((mouseX>posx && mouseX<posx+50) && (mouseY>posy && mouseY<posy+50)){
       isMouseInRect = true
       console.log(posx)
     }else{
       isMouseInRect = false
     }
   }
  setInterval(function () {
    if(!isMouseInRect){
      posx += 10 * dir
    }
    //清空画布的一个矩形区域
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    //真正要用到复杂的绘画的时候，直接从离屏Canvas上拷贝过来
    ctx.drawImage(offCanvas,0,0,offCanvas.width, offCanvas.height,0,0,canvas.width, canvas.height)
    ctx.fillRect(posx, posy, 50, 50)
    if (posx + 50 >= canvas.width) {
      dir = -1
    } else if(posx <=0) {
      dir = 1
    }
  }, 100)
  drawAlot()
  // ctx.drawImage(offCanvas,0,0,offCanvas.width, offCanvas.height,0,0,canvas.width, canvas.height)
</script>
</body>
</html>
